﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Dependency;
using Abp.Events.Bus.Exceptions;
using Abp.Events.Bus.Handlers;
using Abp.UI;
using Abp.Web.Mvc.Authorization;
using WanFang.Authorization;
using WanFang.Authorization.Roles;
using WanFang.Users;
using WanFang.Web.Models.Users;
using WanFang.Authorization.Users;
using WanFang.Web.Models.Account;
using Abp.Extensions;
using Microsoft.AspNet.Identity;
using Abp.Domain.Uow;
using Abp.Authorization.Users;
using System.Collections.Generic;
using WanFang.Test;
using Abp.Organizations;
using System.Text;
using WanFang.Users.Dto;
using AutoMapper;
using System.Web;
using System.IO;
using Aspose.Words;

namespace WanFang.Web.Controllers
{
    [AbpMvcAuthorize]
    public class TestMaterialController : WanFangControllerBase
    {
        private readonly IUserAppService _userAppService;
        private readonly RoleManager _roleManager;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly UserManager _userManager;
        private readonly IMaterialService _materialService;

        public TestMaterialController(IUserAppService userAppService, RoleManager roleManager,
            IUnitOfWorkManager unitOfWorkManager,
            UserManager userManager,
            IMaterialService IMaterialService)
        {
            _userAppService = userAppService;
            _roleManager = roleManager;
            _unitOfWorkManager = unitOfWorkManager;
            _userManager = userManager;
            _materialService = IMaterialService;
        }

        public ActionResult List()
        {
            var lst = _materialService.GetList();
            return View(lst);
        }

        public ActionResult Add()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Add(HttpPostedFileBase FileData)
        {
            if (FileData == null || FileData.ContentLength == 0)
            {
                return Content("文件不存在");
            }
            string ext = Path.GetExtension(FileData.FileName).ToLower();
            DirectoryInfo upDir = new DirectoryInfo( @"Upload\");
            if (!upDir.Exists)
            {
                upDir.Create();
            }
            string uuid = System.Guid.NewGuid().ToString();
            //上传文件到服务器
            string newFileName = uuid + ext;
            FileData.SaveAs(string.Format(@"{0}\{1}", upDir.FullName, newFileName));
            // 解析word
            var doc = new Document(string.Format(@"{0}\{1}", upDir.FullName, newFileName));
            var tables = doc.GetChildNodes(NodeType.Table, true);
            if(tables==null || tables.Count == 0) { 
                throw new Exception("word格式不正确");
            }
            var table = tables[0] as Aspose.Words.Tables.Table;
            if (table.Rows.Count < 3)
            {
                throw new Exception("word格式不正确");
            }
            Material entity = new Material();
            entity.Name = table.Rows[0].Cells[0].GetText().Replace("\a", "").Replace("品   名：", "");
            entity.FNumber = table.Rows[1].Cells[0].GetText().Replace("\a", "").Replace("物料代码：", "");
            entity.Batch = table.Rows[2].Cells[0].GetText().Replace("\a", "").Replace("产品批号：", "");
            _materialService.Add(entity);
            return Json(new ResultMsg());
        }

        public async Task<ActionResult> Update()
        {
            var user = await _userManager.GetUserByIdAsync(AbpSession.UserId.Value);
            var model = new RegisterViewModel
            {
                Name = user.Name,
                Surname = user.Surname,
                EmailAddress = user.EmailAddress,
                UserName=user.UserName
            };
            return View(model);
        }
        [HttpPost]
        public ActionResult Update(RegisterViewModel model)
        {
            if (model.UserName.IsNullOrEmpty() || model.Password.IsNullOrEmpty())
            {
                throw new UserFriendlyException(L("FormIsNotValidMessage"));
            }
            var user = new User
            {
                Name = model.Name,
                Surname = model.Surname,
                EmailAddress = model.EmailAddress,
                IsActive = true
            };
            user.UserName = model.UserName;
            user.Password = new PasswordHasher().HashPassword(model.Password);
            user.Roles = new List<UserRole>();
            foreach (var defaultRole in _roleManager.Roles.Where(r => r.IsDefault).ToList())
            {
                user.Roles.Add(new UserRole { RoleId = defaultRole.Id });
            }
            user.Id = AbpSession.UserId.Value;
            _userManager.Update(user);
            return Json(new ResultMsg());
        }
    }
}